package phapp.springSecurity;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.web.FilterInvocation;

import javacommon.util.SpringContextUtil;
import javacommon.util.StringTool;
//import com.jw.system.model.system.SysLog;
//import com.jw.system.service.common.CommonUtils;
import phapp.model.system.*;
import phapp.service.system.*;

/**
 * 对session失效进行跳转处理
 * 
 */
public class SessionTimeOutFilter implements Filter
{

   public void destroy()
   {
   }

   public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
   {
      //SysLog logBean = null;
      //SysLogManager logManager = null;
      //String SysLoginSeq = "", SysLoginAccount = "";
      Map<String, Object> mapQuery = new HashMap<String, Object>();
      
      SpringAuthUser authUser = null;
      HttpSession userSession = null;
      HttpServletRequest httpRequest = (HttpServletRequest) request;
      HttpServletResponse httpResponse = (HttpServletResponse)response;
      String RequestUri = "", RedirectUrl = "", LoginRequestUrl = "", LoginSubmitUrl = "", TimeoutUrl = "";
      
      //Session不存在则进行创建
      userSession = httpRequest.getSession(true);
      RequestUri = httpRequest.getRequestURI();
      LoginSubmitUrl = httpRequest.getContextPath() + "/j_spring_security_check";
      LoginRequestUrl = httpRequest.getContextPath() + "/login.jsp";
      TimeoutUrl = httpRequest.getContextPath() + "/login.jsp";

      System.out.println("\n------RequestUri[" + RequestUri + "]---\n");
      //处理spring登录提交(j_spring_security_check)
      if(RequestUri.equals(LoginSubmitUrl))
      {
//         //开始登录，设置登录序号(唯一序号)
//         SysLoginSeq = CommonUtils.generateSeq();
//         userSession.setAttribute("USER_LOGIN_SEQ", SysLoginSeq);
//         
//         //记录登录日志，默认失败，成功后更新状态，帐号为空不进行记录
//         SysLoginAccount = request.getParameter("j_username");
//         if(SysLoginAccount != null && SysLoginAccount.length() > 0)
//         {
//            logBean = new SysLog();
//            logManager = (SysLogManager) SpringContextUtil.getBean("sysLogManager");
//            String strLogContent = "系统登录：用户帐号[" + SysLoginAccount + "]";
//            
//            logBean.setOperateResult(1);
//            logBean.setOperateSeq(SysLoginSeq);
//            logBean.setOperateType(SysLog.LOGTYPE_LOGIN);
//            logBean.setOperateContent(strLogContent);
//            logManager.save(logBean);
//         }
         
         //检查验证码是否正确，不正确则重定向到登录页面
         String InputCode = httpRequest.getParameter(SpringSecurityConstant.CODE);
         String SystemCode = (String) httpRequest.getSession().getAttribute(SpringSecurityConstant.SESSION_CODE);
//         if(null == InputCode || null == SystemCode || InputCode.equalsIgnoreCase(SystemCode) == false)
//         {
//            RedirectUrl = httpRequest.getContextPath() + SpringSecurityConstant.VALIDE_ERROR_URL;
//            httpResponse.sendRedirect(RedirectUrl);
//            
////            RequestDispatcher httpDispatcher = httpRequest.getRequestDispatcher(RedirectUrl);
////            if (httpDispatcher != null)
////               httpDispatcher.forward(request, response);
////            else
////               httpResponse.sendRedirect(RedirectUrl);
//
//            System.out.println("VerifyCode error, RedirectUrl[" + RedirectUrl + "]>>>>>>\n\n\n");
//            return;
//         }
//         else
//         {
//            System.out.println("InputCode[" + InputCode + "] SystemCode[" + SystemCode + "]");
//         }
         
      }
      else
      {
         //验证是否登录
         authUser = getSpringAuthUser(httpRequest);
         if(authUser == null)
         {
            //访问以下类型的页面不需要登录
            if(RequestUri.equals(LoginRequestUrl) || RequestUri.equals(TimeoutUrl) ||
               RequestUri.endsWith("code.jsp") || RequestUri.endsWith("return_pass.jsp") || 
               RequestUri.endsWith("resetPassword.do") || RequestUri.endsWith("getUnitInfo.do") ||
               RequestUri.startsWith("/bar/port/BarService/"))
            {
               ;
            }
            else
            {
               //未登录或session超时，重定向到登录页面
               //httpResponse.sendRedirect(LoginRequestUrl);
               //httpResponse.sendRedirect(LoginRequestUrl);
               
               RedirectUrl = TimeoutUrl;
               httpResponse.sendRedirect(RedirectUrl);
               
               System.out.println("\n\n\n>>>>>>Not login, RedirectUrl[" + RedirectUrl + "]>>>>>>\n\n\n");
               return ;
            }
         }
         else
         {
//            //登录成功后仅运行一次
//            SysLoginSeq = (String) userSession.getAttribute("USER_LOGIN_SEQ");
//            if(SysLoginSeq != null)
//            {
//               logManager = (SysLogManager) SpringContextUtil.getBean("sysLogManager");
//               mapQuery.put("operateSeq", SysLoginSeq);
//               List<SysLog> listLogData = logManager.findList(mapQuery);
//               
//               //更新登录状态
//               if(listLogData != null && listLogData.size() == 1)
//               {
//                  logBean = listLogData.get(0);
//                  logBean.setOperateResult(0);
//                  logBean.setOperUserId(Integer.parseInt(loginUser.getUserId()));
//                  logBean.setOperUnitId(Integer.parseInt(loginUser.getUserUnitId()));
//                  logManager.update(logBean);
//               }
//               else
//               {
//                  System.out.println("SessionTimeOutFilter::doFilter - SysLoginSeq[" + SysLoginSeq + "] error\n");
//               }
//               
//               userSession.removeAttribute("USER_LOGIN_SEQ");
//            }
         }
      }
      
      //正常访问(控制权交给spring的filter)
      FilterInvocation filterInvocation = new FilterInvocation(request, response, chain);
      filterInvocation.getChain().doFilter(filterInvocation.getRequest(), filterInvocation.getResponse());
   }
   
   public void init(FilterConfig arg0) throws ServletException
   {
   }
   
   private SpringAuthUser getSpringAuthUser(HttpServletRequest request)
   {
      SpringAuthUser authUser = null;
      SecurityContextImpl securityContextImpl = null;
      HttpSession session = request.getSession(false);  
      
      if(session != null)
      {
         securityContextImpl = (SecurityContextImpl) session.getAttribute("SPRING_SECURITY_CONTEXT");
         if(securityContextImpl != null)
         {
            if(securityContextImpl.getAuthentication() != null)
               authUser = (SpringAuthUser) securityContextImpl.getAuthentication().getPrincipal();
            
            //System.out.println("getAuthentication[" + securityContextImpl.getAuthentication().toString() + "]\n\n\n");
         }
      }
      
      return authUser;
   }

}
